<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useConfigStore } from "@/store/modules/config";
import { showSuccessToast, showToast } from "vant";
import { useI18n } from "vue-i18n";
import { isMobileDevice } from "@/utils/base_index";

const useConfig = useConfigStore();
const { t } = useI18n();

const price = ref(null);
const quantity = ref(null);

// const usdtAmount = ref(0);
// const checkingUSDT = async () => {
//   const amount = await useConfig.ALLOWANCE_USDT();
//   usdtAmount.value = amount;
// };

// const allowance = async () => {
//   console.log("授权");

//   // 先检查一遍授权 如果额度足够 就不用授权了
//   await checkingUSDT();
//   if (usdtAmount.value > 0) {
//     return;
//   }

//   const amount = useConfig.web3.utils.toWei(10000000000, "ether");
//   const data = useConfig.usdtContract.methods
//     .approve(useConfig.masterContractAddress, amount)
//     .encodeABI();
//   const params = {
//     to: useConfig.usdtContractAddress,
//     from: useConfig.getAccount,
//     value: useConfig.getWbe3.utils.toHex(0),
//     data
//   };
//   useConfig.getWbe3.eth
//     .sendTransaction(params)
//     .on("transactionHash", function (hash) {
//       console.log("hash", hash);
//       showSuccessToast(t("bigv.success"));
//     })
//     .on("receipt", receipt => {
//       console.log("receipt", receipt);
//       checkingUSDT();
//     })
//     .catch(error => {
//       console.error("error:", error);
//     });
// };

// 查询是否有订单存在
const isOrder = ref(true);
const loadData = async () => {
  const res = await useConfig.masterContract.methods
    .getTradeCurrent(useConfig.account)
    .call();
  const { sellAddress } = res;
  if (sellAddress === "0x0000000000000000000000000000000000000000") {
    isOrder.value = false;
  }
  console.log(res);
};

// 手续费
const totalFee = ref(0);
const getTotalFee = async () => {
  const fee = await useConfig.masterContract.methods
    .totalFee(useConfig.account)
    .call();
  totalFee.value = useConfig.web3.utils.toNumber(fee);
};

// 预支到合约
const estimatedArrival = computed(() => {
  // 卖出的数量+卖出的数量*手续费
  const _quantity = Number(quantity.value || 0);
  const _totalFee = totalFee.value / 100;
  return _quantity + _quantity * _totalFee;
});

// 收到
const arrival = computed(() => {
  try {
    const a = price.value * quantity.value;
    return a;
  } catch (error) {
    return "--";
  }
});

// 创建
const createOrder = async () => {
  if (!price.value || !quantity.value) return;

  const _priceWei = useConfig.web3.utils.toWei(price.value, "ether");
  const _quantityWei = useConfig.web3.utils.toWei(quantity.value, "ether");

  const data = useConfig.masterContract.methods
    .sell(_priceWei, _quantityWei)
    .encodeABI();
  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }
  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      loadData();
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("创建订单");
};

onMounted(() => {
  getTotalFee();
  loadData();
  // checkingUSDT();
});
</script>

<template>
  <div class="app-container">
    <h1>创建订单</h1>
    <div>余额: {{ useConfig.balance }}{{ useConfig.name }}</div>

    <div>
      <van-cell-group inset>
        <van-field
          v-model="price"
          type="number"
          placeholder="输入"
          label="单价(USDT)"
        />
        <van-field
          v-model="quantity"
          type="digit"
          placeholder="输入"
          :label="`数量(${useConfig.name})`"
        />
      </van-cell-group>
    </div>
    <div>手续费:{{ totalFee }}</div>
    <div>预支到合约:{{ estimatedArrival }}</div>
    <div>将收到(单价*数量):{{ arrival }}</div>

    <div>
      <van-button block type="primary" :disabled="isOrder" @click="createOrder"
        >创建订单</van-button
      >
    </div>
  </div>
</template>

<style lang="less" scoped>
.app-container {
  padding: 20px;
  color: #fff;
  & > div {
    padding: 10px 0;
  }
}
</style>
